package com.alibaba.citrus.cr.order.open.api.facade.transfer;

import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.order.open.api.facade.common.model.WmsOrderMessageDTO;
import com.alibaba.citrus.cr.order.open.api.facade.convert.WarehouseConvert;
import com.alibaba.citrus.cr.order.open.api.facade.model.TransferOrder;
import com.alibaba.citrus.cr.order.open.api.facade.model.TransferOrderQueryRequest;
import com.alibaba.citrus.cr.order.open.api.facade.model.TransferSubOrder;
import com.alibaba.citrus.cr.order.open.api.facade.transferorder.TransferOrderQueryService;
import com.alibaba.citrus.cr.unified.inventory.contants.FeaturesKey;
import com.alibaba.citrus.cr.unified.inventory.contants.MessageBusinessCodeEnum;
import com.alibaba.citrus.cr.unified.inventory.contants.MessageEventCodeEnum;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.CancelOrderInnerReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.response.fulfillment.BatchCancelFulfillmentOrderResponse;
import com.alibaba.cloud.retail.delivery.api.model.delivery.response.fulfillment.FulfillmentGetRes;
import com.alibaba.cloud.retail.delivery.api.model.fulfillment.request.SearchFulfillmentOrderInnerReq;
import com.alibaba.cloud.retail.delivery.api.model.fulfillment.request.SearchFulfullmentOrderReq;
import com.alibaba.cloud.retail.delivery.api.service.bcfulfillment.FulfillmentOrderAbilityService;
import com.alibaba.cloud.retail.wms.api.model.orders.common.WarehousingOrderDTO;
import com.alibaba.cloud.retail.wms.api.model.orders.request.WmsOrderQueryRequest;
import com.alibaba.cloud.retail.wms.api.model.orders.response.WarehousingOrdersQueryResponse;
import com.alibaba.cloud.retail.wms.api.service.orders.WarehousingOrderReadService;
import com.alibaba.cz.base.model.store.CargoZoneSDO;
import com.alibaba.cz.base.tool.DateFormatUtil;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.allocateorderdomain.dto.UpdateStatusRequest;
import com.epoch.app.crunifiedinventory.allocateorderdomain.service.AllocateOrderDomainService;
import com.epoch.app.crunifiedinventory.allocateorderstandardmessage.service.AllocateOrderStandardMessageService;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.model.AllocateApplyOrder;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorder.service.AllocateApplyOrderService;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.dto.AllocateApplyOrderDetailLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.model.AllocateApplyOrderDetail;
import com.epoch.app.crunifiedinventory.domain.allocateapplyorderdetail.service.AllocateApplyOrderDetailService;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.AllocateOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorder.model.AllocateOrder;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.dto.QueryListByIdsRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.dto.QueryListByIdsResponse;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.model.AllocateOrderDetail;
import com.epoch.app.crunifiedinventory.domain.allocateorderdetail.service.AllocateOrderDetailService;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderStandardMessageDTO;
import com.epoch.app.crunifiedinventory.model.enums.FulfillmentTypeEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.mninventorycenter.model.dto.*;
import com.epoch.app.mninventorycenter.transferforecastorderwrite.service.TransferForecastOrderWriteService;
import com.epoch.app.mninventorycenter.transferorderwrite.service.TransferOrderWriteService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yifei
 * @since 2024/1/15
 */
@Service
public class TransferCenterCommonService {
    private static final Log log = Log.getLogger(TransferCenterCommonService.class);

    @Resource
    private TransferOrderQueryService transferOrderQueryService;

    @Resource
    private AllocateApplyOrderService allocateApplyOrderService;

    @Resource
    private AllocateApplyOrderDetailService allocateApplyOrderDetailService;

    @Resource
    private AllocateOrderService allocateOrderService;

    @Resource
    private AllocateOrderDetailService allocateOrderDetailService;

    @Resource
    private TransferForecastOrderWriteService transferForecastOrderWriteService;

    @Resource
    private TransferOrderWriteService transferOrderWriteService;

    @DubboReference
    private WarehousingOrderReadService warehousingOrderReadService;

    @Resource
    private AllocateOrderDomainService allocateOrderDomainService;
    @Resource
    private AllocateOrderStandardMessageService allocateOrderStandardMessageService;

    @Resource
    private WarehouseConvert warehouseConvert;

    @Resource
    private FulfillmentOrderAbilityService fulfillmentOrderAbilityService;

    public TransferOrder getTransferOrderInfo(String bizOrderId) {
        log.info("TransferCenterCommonService_getTransferOrderInfo_bizOrderId:{}", bizOrderId);
        TransferOrderQueryRequest transferOrderQueryRequest = new TransferOrderQueryRequest();
        transferOrderQueryRequest.setTransferOrderCode(bizOrderId);
        Result<TransferOrder> transferOrderResult = transferOrderQueryService.query(transferOrderQueryRequest);
        log.info("TransferCenterCommonService_getTransferOrderInfo_transferOrderResult:{}", JSON.toJSONString(transferOrderResult));
        if (transferOrderResult == null || transferOrderResult.getResult() == null) {
            return null;
        }
        return transferOrderResult.getResult();
    }

    public TransferOrder getTransferOrderInfoByThirdAllocateOrderId(String thirdAllocateOrderId) {
        log.info("TransferCenterCommonService_getTransferOrderInfoByThirdAllocateOrderId_thirdAllocateOrderId:{}", thirdAllocateOrderId);
        TransferOrderQueryRequest transferOrderQueryRequest = new TransferOrderQueryRequest();
        transferOrderQueryRequest.setThirdAllocateOrderId(thirdAllocateOrderId);
        Result<TransferOrder> transferOrderResult = transferOrderQueryService.query(transferOrderQueryRequest);
        log.info("TransferCenterCommonService_getTransferOrderInfoByThirdAllocateOrderId_transferOrderResult:{}", JSON.toJSONString(transferOrderResult));
        if (transferOrderResult == null || transferOrderResult.getResult() == null) {
            return null;
        }
        return transferOrderResult.getResult();
    }

    public List<WarehousingOrderDTO> queryWmsOrder(String bizOrderId) {
        log.info("TransferCenterCommonService_queryWmsOrder_bizOrderId:{}", bizOrderId);
        WmsOrderQueryRequest request = new WmsOrderQueryRequest();
        request.setBizOrderId(bizOrderId);
        request.setContainSubOrders(true);
        com.alibaba.cz.base.tool.result.Result<WarehousingOrdersQueryResponse> result = warehousingOrderReadService.queryWmsOrderByOtherOrder(request);
        log.info("TransferCenterCommonService_queryWmsOrder_result:{}", JSON.toJSONString(result));
        if (!result.isSuccess() || result.getResult() == null) {
            log.error("OutBoundMessageProcessServiceImpl_queryWmsOrder_error|bizOrderId:" + bizOrderId);
            throw new RuntimeException("获取出入库单失败");
        }
        List<WarehousingOrderDTO> warehousingOrders = result.getResult().getWarehousingOrders();
        return Nullable.stream(warehousingOrders).filter(x -> {
            if (Objects.isNull(x.getOrderStatus())) {
                return false;
            }
            return x.getOrderStatus() != 11 && x.getOrderStatus() != 12;
        }).collect(Collectors.toList());
    }

    public List<WarehousingOrderDTO> queryWmsOrderByWmsOrderId(String wmsOrderId) {
        log.info("TransferCenterCommonService_queryWmsOrderByWmsOrderId_wmsOrderId:{}", wmsOrderId);
        WmsOrderQueryRequest request = new WmsOrderQueryRequest();
        request.setWmsOrderId(wmsOrderId);
        request.setContainSubOrders(true);
        com.alibaba.cz.base.tool.result.Result<WarehousingOrdersQueryResponse> result = warehousingOrderReadService.queryWmsOrderByOtherOrder(request);
        log.info("TransferCenterCommonService_queryWmsOrderByWmsOrderId_result:{}", JSON.toJSONString(result));
        if (!result.isSuccess() || result.getResult() == null) {
            log.error("OutBoundMessageProcessServiceImpl_queryWmsOrderByWmsOrderId_error|bizOrderId:" + wmsOrderId);
            throw new RuntimeException("获取出入库单失败");
        }
        return result.getResult().getWarehousingOrders();
    }

    public List<AllocateApplyOrderDetail> getAllocateApplyOrderDetailList(String allocateApplyOrderId) {
        log.info("TransferCenterCommonService_getAllocateApplyOrderDetailList_allocateApplyOrderId:{}", allocateApplyOrderId);
        if (allocateApplyOrderId == null) {
            return null;
        }
        AllocateApplyOrderDetailLoadListRequest request = new AllocateApplyOrderDetailLoadListRequest();
        request.setAllocateApplyOrderId(Integer.valueOf(allocateApplyOrderId));
        Result<List<AllocateApplyOrderDetail>> listResult = allocateApplyOrderDetailService.loadAllocateApplyOrderDetailList(request);
        log.info("TransferCenterCommonService_getAllocateApplyOrderDetailList_listResult:{}", listResult);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())) {
            return null;
        }
        return listResult.getResult();
    }

    public void updateTransferSubBizFeatures(String allocateOrderCode, Map<String, SubFeaturesRequest> map) {
        FeaturesUpdateRequest request = new FeaturesUpdateRequest();
        request.setMainOrderCode(allocateOrderCode);
        request.setSubBizFeaturesToUpdate(map);
        log.info("TransferCenterCommonService_updateSubBizFeatures_request:{}", JSON.toJSONString(request));
        Result<Void> result = transferOrderWriteService.updateFeatures(request);
        if (result == null || !result.isSuccess()) {
            log.error("TransferCenterCommonService_updateSubBizFeatures_allocateOrderCode:{}", allocateOrderCode);
            throw new RuntimeException("更新调拨子单标失败");
        }
        //出入库明细 更新features数量时 也需要发消息
        try{
            AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
            if (StringUtils.isNotBlank(allocateOrderCode)){
                allocateOrderLoadListRequest.setCode(allocateOrderCode);
                Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    AllocateOrder allocateOrder = listResult.getResult().get(0);
                    AllocateOrderStandardMessageDTO messageDTO = AllocateOrderStandardMessageDTO.builder()
                            .keyword(allocateOrder.getCode())
                            .eventCode(MessageEventCodeEnum.EDIT.getCode())
                            .businessCode(MessageBusinessCodeEnum.ALLOCATE_ORDER.getCode())
                            .businessType(allocateOrder.getBusinessType())
                            .fromSys(allocateOrder.getFromSys())
                            .eventTime(new Date())
                            .build();
                    allocateOrderStandardMessageService.sendAllocateOrderStandardMessage(messageDTO);
                }
            }
        }catch (Throwable e){
            log.error("updateTransferSubBizFeatures_send_standard_message_error",e);
        }
        //更新调拨单本身主子单状态
        //只有大仓相关的才用新方式推进状态
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setCode(allocateOrderCode);
        Result<List<AllocateOrder>> allocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        log.info("updateTransferSubBizFeatures_loadAllocateOrderList_result{}",JSON.toJSONString(allocateOrderList));
        if (allocateOrderList == null || CollectionUtils.isEmpty(allocateOrderList.getResult())){
            return;
        }
//        //TODO 更新状态时只允许有试点范围内仓的调拨单
//        boolean needUpdateStatus = Arrays.asList(FulfillmentTypeEnum.VIRTUAL_TRANSFER, FulfillmentTypeEnum.CURRENT2PILOT, FulfillmentTypeEnum.PILOT2PILOT, FulfillmentTypeEnum.PILOT2CURRENT)
//                .stream().anyMatch(fulfillmentTypeEnum -> fulfillmentTypeEnum.getValue().toString().equals(allocateOrderList.getResult().get(0).getFulfillmentTypeCode()));
//        log.info("updateStatus:{}",needUpdateStatus);
//        if (needUpdateStatus){
//            UpdateStatusRequest updateStatusRequest = UpdateStatusRequest.builder().code(allocateOrderCode).build();
//            Result<Void> updateStatusResult = allocateOrderDomainService.updateStatus(updateStatusRequest);
//            log.info("updateStatus_result:{}",JSON.toJSONString(updateStatusResult));
//        }
    }

    public void updateApplyTransferSubBizFeatures(String mainOrderId, List<SubFeaturesRequest> subList) {
        log.info("TransferCenterCommonService_updateApplyTransferSubBizFeatures_mainOrderId:{}|subList:{}", mainOrderId, JSON.toJSONString(subList));
        FeaturesUpdateRequest request = new FeaturesUpdateRequest();
        request.setMainOrderId(mainOrderId);
        request.setSubList(subList);
        Result<Void> result = transferForecastOrderWriteService.updateFeatures(request);
        if (result == null || !result.isSuccess()) {
            log.error("TransferCenterCommonService_updateApplyTransferSubBizFeatures_allocateApplyOrderCode:{}", request.getMainOrderCode());
            throw new RuntimeException("更新调拨子单标失败");
        }

    }

    public List<AllocateOrder> getTransferOrderList(String transferApplyOrderId, String relatedAllocateOrderCode) {
        AllocateOrderLoadListRequest request = new AllocateOrderLoadListRequest();
        if (StringUtils.isNotBlank(transferApplyOrderId)) {
            request.setAllocateApplyOrderId(transferApplyOrderId);
        } else if (StringUtils.isNotBlank(relatedAllocateOrderCode)) {
            request.setRelatedAllocateOrderCode(relatedAllocateOrderCode);
        }
        log.info("TransferCenterCommonService_getTransferOrderList_request:{}", JSON.toJSONString(request));
        Result<List<AllocateOrder>> listResult = allocateOrderService.loadAllocateOrderList(request);
        log.info("TransferCenterCommonService_getTransferOrderList_listResult:{}", JSON.toJSONString(listResult));
        if (listResult == null) {
            log.error("TransferCenterCommonService_getTransferOrderList_error:{}", JSON.toJSONString(transferApplyOrderId));
            throw new FacadeException("获取调拨主单数据失败");
        }
        return listResult.getResult();
    }

    public List<AllocateOrderDetail> getTransferOrderDetailListByRelatedCode(String relatedAllocateOrderCode) {
        List<AllocateOrder> transferOrderList = getTransferOrderList(null, relatedAllocateOrderCode);
        if (CollectionUtils.isEmpty(transferOrderList)) {
            return new ArrayList<>(0);
        }
        List<Long> idList = transferOrderList.stream().map(AllocateOrder::getId).collect(Collectors.toList());
        return getTransferOrderDetailList(idList);
    }

    public List<AllocateOrderDetail> getTransferOrderDetailList(String transferApplyOrderId) {
        List<AllocateOrder> transferOrderList = getTransferOrderList(transferApplyOrderId, null);
        if (CollectionUtils.isEmpty(transferOrderList)) {
            return new ArrayList<>(0);
        }
        List<Long> idList = transferOrderList.stream().map(AllocateOrder::getId).collect(Collectors.toList());
        return getTransferOrderDetailList(idList);
    }

    public List<AllocateOrderDetail> getTransferOrderDetailList(List<Long> allocateOrderIdList) {
        log.info("TransferCenterCommonService_getTransferDetailList_allocateOrderIdList:{}", allocateOrderIdList);
        QueryListByIdsRequest request = new QueryListByIdsRequest();
        request.setAllocateOrderIds(allocateOrderIdList);
        QueryListByIdsResponse response = allocateOrderDetailService.queryListByIds(request);
        log.info("TransferCenterCommonService_getTransferDetailList:{}", JSON.toJSONString(response));
        if (response == null) {
            log.error("TransferCenterCommonService_getTransferDetailList_error:{}", JSON.toJSONString(allocateOrderIdList));
            throw new FacadeException("获取调拨子单数据失败");
        }
        return response.getResult();
    }

    public Boolean createFreightYardTransfer(WmsOrderMessageDTO wmsOrderDTO, List<WarehousingOrderDTO> warehousingOrderList, TransferOrder orderInfo) {
        WarehousingOrderDTO dto = warehousingOrderList.stream().filter(wmsOrder -> wmsOrderDTO.getWarehousingOrderId().equals(wmsOrder.getWarehousingOrderId()))
                .findFirst().orElse(null);
        if (dto == null) {
            log.error("TransferCenterCommonService_createFreightYardTransfer_dto_null");
            return Boolean.TRUE;
        }
        //如果入库单的物料凭证没有回写就不创建货场提货单
        if (StringUtils.isBlank(dto.getOutWarehousingOrderId())){
            log.error("TransferCenterCommonService_createFreightYardTransfer_outWarehousingOrder_null");
            return Boolean.FALSE;
        }
        TransferOrderCreateRequest request = buildTransferOrderCreateRequest(dto, orderInfo);
        if (request == null) {
            log.error("TransferCenterCommonService_createFreightYardTransfer_request_null");
            return Boolean.TRUE;
        }
        log.info("TransferCenterCommonService_createFreightYardTransfer_request:{}", JSON.toJSONString(request));
        Result<TransferOrderCreateResponse> response = transferOrderWriteService.createAllocateOrder(request);
        log.info("TransferCenterCommonService_createFreightYardTransfer_response:{}", JSON.toJSONString(response));
        if (response == null) {
            return Boolean.FALSE;
        }
        return response.isSuccess();
    }

    public List<FulfillmentGetRes> getFulfillmentOrder(String sourceOrderNo) {
        if (StringUtils.isBlank(sourceOrderNo)) {
            return Lists.newArrayListWithCapacity(0);
        }
        SearchFulfullmentOrderReq req = new SearchFulfullmentOrderReq();
        req.setSourceOrderNo(sourceOrderNo);
        log.info("TransferCenterCommonService_getFulfillmentOrder_req:{}", JSON.toJSONString(req));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> result = fulfillmentOrderAbilityService.searchFulfullmentOrder(req);
        log.info("TransferCenterCommonService_getFulfillmentOrder_result:{}", JSON.toJSONString(result));
        if (result.isSuccess()) {
            return result.getResult();
        }
        return Lists.newArrayListWithCapacity(0);
    }

    public void cancelReverseFulfillmentOrder(String fulfillmentOrderNo) {
        CancelOrderInnerReq req = new CancelOrderInnerReq();
        req.setFulfillmentOrderNo(fulfillmentOrderNo);
        req.setUpdater("系统");
        log.info("TransferCenterCommonService_cancelReverseFulfillmentOrder_req:{}", JSON.toJSONString(req));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<BatchCancelFulfillmentOrderResponse> result = fulfillmentOrderAbilityService.cancelOrderInner(req);
        log.info("TransferCenterCommonService_cancelReverseFulfillmentOrder_result:{}", JSON.toJSONString(result));
        if (!result.isSuccess()) {
            log.error("TransferCenterCommonService_cancelReverseFulfillmentOrder_error:{}", result.getMessage());
        }
    }

    public void cancelFulfillmentOrder(String wmsOrderId) {
        List<FulfillmentGetRes> fulfillmentOrder = getFulfillmentOrder(wmsOrderId);
        if (CollectionUtils.isNotEmpty(fulfillmentOrder)) {
            cancelReverseFulfillmentOrder(fulfillmentOrder.get(0).getFulfillmentOrderNo());
        }
    }

    private TransferOrderCreateRequest buildTransferOrderCreateRequest(WarehousingOrderDTO dto, TransferOrder orderInfo) {
        Map<String, CargoZoneSDO> cargoZoneSDOMap = warehouseConvert.getCargoZoneSDOMap(Lists.newArrayList(orderInfo.getReceiveAreaId()));
        if (cargoZoneSDOMap.get(orderInfo.getReceiveAreaId()) == null) {
            log.error("TransferCenterCommonService_buildTransferOrderCreateRequest_cargoZoneSDOMap_receiveAreaId:" + orderInfo.getReceiveAreaId());
            return null;
        }
        TransferOrderCreateRequest request = new TransferOrderCreateRequest();
        request.setFromSys(StringUtils.isBlank(orderInfo.getFromSys()) ? "APP_OMNI" : orderInfo.getFromSys());
        request.setBusinessType(StringUtils.isBlank(orderInfo.getBusinessType()) ? "11" : orderInfo.getBusinessType());
        request.setRequestId(dto.getWarehousingOrderId());
        request.setThirdAllocateOrderId(dto.getWarehousingOrderId());
        request.setRelatedAllocateOrderCode(orderInfo.getTransferOrderCode());
        request.setSubmitFlag(Boolean.TRUE.toString());
        request.setFulfillmentTypeCode(FulfillmentTypeEnum.PILOT2PILOT.getValue().toString());
        request.setAutoFulfillment(Boolean.TRUE);
        //request.setOrderTag("");
        request.setPriority("1");
        request.setTransferOrderType(AllocateOrderTypeEnum.FREIGHT_YARD_PICKUP.getType());
        request.setApplyOrgId(StringUtils.isBlank(orderInfo.getApplyOrgId()) ? "6000" : orderInfo.getApplyOrgId());
        request.setProductGroupCode(StringUtils.isBlank(orderInfo.getProductGroupCode()) ? "11" : orderInfo.getProductGroupCode());
        request.setDeliveryLogicWareCode(orderInfo.getTransferWarehouseId());
        request.setReceiveLogicWareCode(cargoZoneSDOMap.get(orderInfo.getReceiveAreaId()).getCode());
        request.setCreator("system");
        String date = DateFormatUtil.formatToyyyMMdd(new Date());
        request.setTakeEffectDate(date);
        request.setOrderDate(date);
        request.setExpectedDeliveryDate(date);
        request.setShipMethodCode("01");
        //request.setHeadRemark("");
        request.setReturnFlag(Boolean.FALSE.toString());
        //将入库单号写到货场提货单的bizFeatures中
        Map<String,String> bizFeatures = Maps.newHashMap();
        bizFeatures.put(FeaturesKey.ORIGIN_PLAN_WMS_ORDER_ID,dto.getWarehousingOrderId());
        JSONObject bizFeatureJsonObject = new JSONObject();
        bizFeatureJsonObject.put(FeaturesKey.ORIGIN_PLAN_WMS_ORDER_ID,dto.getWarehousingOrderId());
        request.setBizFeatures(bizFeatureJsonObject.toJSONString());
        List<TransferOrderDetailRequest> detailRequestList = buildTransferOrderDetailRequestList(dto, orderInfo);
        if (CollectionUtils.isEmpty(detailRequestList)) {
            log.error("TransferCenterCommonService_buildTransferOrderCreateRequest_detailRequestList_null");
            return null;
        }
        request.setTransferOrderDetailList(detailRequestList);
        return request;
    }

    private List<TransferOrderDetailRequest> buildTransferOrderDetailRequestList(WarehousingOrderDTO dto, TransferOrder orderInfo) {
        Map<String, TransferSubOrder> transferSubOrderMap = orderInfo.getDetailList().stream().collect(Collectors.toMap(TransferSubOrder::getLineNo, a -> a, (a, b) -> a));
        List<TransferOrderDetailRequest> detailRequestList = dto.getWmsSubOrders().stream().map(detail -> {
            if (transferSubOrderMap.get(detail.getBizSubOrderId()) == null) {
                return null;
            }
            TransferOrderDetailRequest request = new TransferOrderDetailRequest();
            request.setOutDetailLineNo(detail.getWmsSubOrderId());
            Map<String, String> featureMap = detail.getFeatureMap();
            if (MapUtils.isEmpty(featureMap)) {
                log.error("TransferCenterCommonService_buildTransferOrderDetailRequestList_goodsCode_null");
                return null;
            }
            request.setGoodsCode(featureMap.get("goodsCode"));
            request.setQuantity(detail.getGoodsQuantity().toString());
            request.setUnit(detail.getGoodsUnit());
            request.setProductDate(detail.getDom() == null ? null : DateFormatUtil.formatToyyyMMdd(detail.getDom()));
            request.setRelatedAllocateSubOrderNo(transferSubOrderMap.get(detail.getBizSubOrderId()).getLineNo());
            Map<String, String> map = new HashMap<>();
            map.put("batchNo", detail.getBatchNo());
            String bizUnitRatio = Optional.ofNullable(transferSubOrderMap.get(detail.getBizSubOrderId())).map(TransferSubOrder::getBizFeatures)
                    .orElse(Maps.newHashMap())
                    .get(FeaturesKey.BIZ_UNIT_RATIO);
            if (StringUtils.isNotBlank(bizUnitRatio)){
                map.put(FeaturesKey.BIZ_UNIT_RATIO,bizUnitRatio);
            }
            request.setBizFeatures(JSON.toJSONString(map));
            return request;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return detailRequestList;
    }

    public void updateWmsInfo(){

    }
}
